package com.linkage.jz.bankruptcy.activity.Project;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingReadMeActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.GetPwdOneActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.PhoneLoginActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.fragment.Project.MyProFragment;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.SignUtil;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.jz.bankruptcy.widget.datepicker.CustomDatePicker;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * A login screen that offers login via email/password.
 */
public  class ZQSetTimeActivity extends BaseCreateActivity implements OnClickListener{
    private static final String TAG = PersonSettingReadMeActivity.class.getSimpleName();
    private Button topBtn01, topBtn02;
    private LinearLayout re_stime,re_etime;
    private int date_type = -1;

    private ShapeLoadingDialog shapeLoadingDialog ;
    @Override
    public void initData() {
        now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.YEAR, 10);
        tenYearLater = calendar.getTime();
    }

    @Override
    public void setListener() {

        top_back.setOnClickListener(this);
    }

    @Override
    public void initTitle() {
        top_title = findViewById(R.id.top_title);
        top_mune = findViewById(R.id.top_mune);
        top_title.setText("修改申报时间");
        top_mune.setVisibility(View.GONE);
        top_mune1.setVisibility(View.VISIBLE);
        top_mune1.setText("完成");
        top_mune1.setOnClickListener(this);
    }
    private CustomDatePicker mDatePicker;
    private Date now, tenYearLater;//日期选择跨度10年（可修改）
    private int mTimeMode = 0; // 0：时间点， 1：时间段
    private long mTimeStart = -1, mTimeEnd = -1, mTime = -1; // 开始时间、结束时间、时间
    @Override
    public void initView() {
        tv_stime = findViewById(R.id.tv_stime);
        tv_etime = findViewById(R.id.tv_etime);

        re_stime = findViewById(R.id.re_stime);
        re_etime = findViewById(R.id.re_etime);

        tv_stime.setText(mstime);
        tv_etime.setText(metime);

        tv_stime.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                date_type = 1;
                mDatePicker = new CustomDatePicker(ZQSetTimeActivity.this, new CustomDatePicker.Callback() {
                    @Override
                    public void onTimeSelected(long timestamp) {
                        mTimeEnd = timestamp;
                        tv_stime.setText(DateFormatUtils.long2Str(timestamp, true));
                    }
                }, now.getTime(), tenYearLater.getTime());
                mDatePicker.setCancelable(false);
                mDatePicker.setCanShowPreciseTime(true);
                mDatePicker.setScrollLoop(false);
                mDatePicker.setCanShowAnim(false);
                mDatePicker.show(DateFormatUtils.long2Str(mTimeEnd, true));

            }
        });

        tv_etime.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                date_type = 2;
                mDatePicker = new CustomDatePicker(ZQSetTimeActivity.this, new CustomDatePicker.Callback() {
                    @Override
                    public void onTimeSelected(long timestamp) {
                        mTimeEnd = timestamp;
                        tv_etime.setText(DateFormatUtils.long2Str(timestamp, true));
                    }
                }, now.getTime(), tenYearLater.getTime());
                mDatePicker.setCancelable(false);
                mDatePicker.setCanShowPreciseTime(true);
                mDatePicker.setScrollLoop(false);
                mDatePicker.setCanShowAnim(false);
                mDatePicker.show(DateFormatUtils.long2Str(mTimeEnd, true));

            }
        });
    }


    TextView top_title,tv_stime,tv_etime,top_mune1;
    Button top_back,top_mune;
    private static String mProID;
    private static String mstime, metime;

    public static void start(Context context, String proID, String stime, String etime) {
        Intent intent = new Intent(context, ZQSetTimeActivity.class);
        mProID = proID;
        mstime = stime;
        metime = etime;
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.activity_zq_settime);

        initview();
        shapeLoadingDialog = new ShapeLoadingDialog(this);
        ActionBar bar = this.getActionBar();
        if(bar != null){
            bar.hide();
        }

        init();
        super.onCreate(savedInstanceState);
    }

    //初始化视图
    private void initview() {
        //登录层、下拉层、其它登录方式层



        top_back = findViewById(R.id.top_back);
        top_mune = findViewById(R.id.top_mune);
        top_mune1 =findViewById(R.id.top_mune1);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_mune1:
                //返回
                saveData();
                break;
            case R.id.top_back:
                finish();
                break;
            default:
                break;
        }
    }

    private void init(){


//        topBtn01 = (Button) this.findViewById(R.id.id_dcphGroup_topBtn01);
//        topBtn02 = (Button) this.findViewById(R.id.id_dcphGroup_topBtn02);
//        topBtn01.setOnClickListener(this);
//        topBtn02.setOnClickListener(this);

    }

    public void saveData()
    {



        String strStime = "";
        String strEtime = "";

        strStime  = tv_stime.getText().toString();
        strEtime  = tv_etime.getText().toString();

        if("".equalsIgnoreCase(strStime))
        {
            Toast.makeText(ZQSetTimeActivity.this,
                    "开始时间不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        if(getTimeCompareSize(strStime,strEtime) == 1)
        {
            Toast.makeText(ZQSetTimeActivity.this,"结束时间不能早于开始时间",Toast.LENGTH_LONG).show();
            return;
        }

        strStime = Utils.Date2timeStamp(strStime,"yyyy-MM-dd HH:mm");
        if(!"".equalsIgnoreCase(strEtime)) {
            strEtime = Utils.Date2timeStamp(strEtime, "yyyy-MM-dd HH:mm");
        }else{
            strEtime = "";
        }

        shapeLoadingDialog.setLoadingText("提交信息中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            getToken();
            return;
        }

        OkHttpClient okHttpClient = new OkHttpClient();
        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";

        String str_switch_show = "";


        String sign = SignUtil.createSign(Consts.APPKEY,params);
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)

                .add("claimFilingStartTime", strStime)
                .add("claimFilingEndTime", strEtime)
                .add("projectId", mProID)



                .build();

        String url = Consts.WEBURL_SETFILINGTIME;

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();


                shapeLoadingDialog.dismiss();
                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ZQSetTimeActivity.this,
                                        "提交成功",Toast.LENGTH_SHORT).show();
                                EventBus.getDefault().post(Consts.EVENTFLOW);
                                finish();

                            }

                        });
                    }else{
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ZQSetTimeActivity.this,
                                        "提交失败",Toast.LENGTH_SHORT).show();


                            }

                        });
                    }

                    str = "";
                }catch (Exception ex)
                {

                    ex.printStackTrace();
                }
            }
        });


    }
//    public void setDate(){
//
//        //通过自定义控件AlertDialog实现
//        AlertDialog.Builder builder = new AlertDialog.Builder(ZQSetTimeActivity.this);
//        View view = (LinearLayout) getLayoutInflater().inflate(R.layout.layout_dateshow, null);
//        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
//        //设置日期简略显示 否则详细显示 包括:星期\周
//        datePicker.setCalendarViewShown(false);
//        //初始化当前日期
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTimeInMillis(System.currentTimeMillis());
//        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
//                calendar.get(Calendar.DAY_OF_MONTH), null);
//        //设置date布局
//        builder.setView(view);
//        builder.setTitle("设置日期信息");
//        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                //日期格式
//                StringBuffer sb = new StringBuffer();
//                sb.append(String.format("%d-%02d-%02d ",
//                        datePicker.getYear(),
//                        datePicker.getMonth() + 1,
//                        datePicker.getDayOfMonth()));
////                        oplandate.setText(sb);
////                        //赋值后面闹钟使用
//                int mYear = datePicker.getYear();
//                int mMonth = datePicker.getMonth();
//                int mDay = datePicker.getDayOfMonth();
//
//
//                if(date_type ==1)
//                {
//
//                    tv_stime.setText(sb.toString() + " 00:00");
//                }else if(date_type ==2){
//                    tv_etime.setText(sb.toString() + " 00:00");
//                }
//                dialog.cancel();
//            }
//        });
//        builder.setNegativeButton("取  消", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.cancel();
//            }
//        });
//        builder.create().show();
//    }


    public static int getTimeCompareSize(String startTime, String endTime){
        int i=0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//年-月-日 时-分
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 1 结束时间小于开始时间 2 开始时间与结束时间相同 3 结束时间大于开始时间
            if (date2.getTime()<date1.getTime()){
                i= 1;
            }else if (date2.getTime()==date1.getTime()){
                i= 2;
            }else if (date2.getTime()>date1.getTime()){
                //正常情况下的逻辑操作.
                i= 3;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return  i;
    }

}


